package com.example.ovulationperiodtracker.fragment;

import static com.just.agentweb.AgentWebUtils.dp2px;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.ovulationperiodtracker.Allactivity.MainActivity;
import com.example.ovulationperiodtracker.R;
import com.example.ovulationperiodtracker.databinding.FragmentCalendarBinding;
import com.example.ovulationperiodtracker.databinding.FragmentChartBinding;
import com.example.ovulationperiodtracker.utils.CalendarUtils;
import com.example.ovulationperiodtracker.utils.MyLog;
import com.example.ovulationperiodtracker.utils.SexStatisticsUtils;
import com.example.ovulationperiodtracker.view.ChartTabView;
import com.example.ovulationperiodtracker.view.NoteUtils;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.necer.base.BaseFragment;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ChartFragment extends BaseFragment<FragmentChartBinding> {


    private static final DateTimeFormatter MM_DD_FORMATTER = DateTimeFormatter.ofPattern("MM-dd");
    private int index = 0;

    @Override
    public FragmentChartBinding createBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentChartBinding.inflate(inflater);
    }

    @Override
    protected void onCreated() {


        binding.chartTabView.setOnChartTabListener(new ChartTabView.OnChartTabListener() {
            @Override
            public void onClickTab(int position) {

                binding.ll0.setVisibility(View.GONE);
                binding.ll1.setVisibility(View.GONE);
                binding.ll2.setVisibility(View.GONE);
                binding.ll3.setVisibility(View.GONE);

                index = position;

                if (index == 0) {
                    initTab0();
                } else if (index == 1) {
                    initTab1();
                } else if (index == 2) {
                    initTab2();
                } else if (index == 3) {
                    initTab3();
                }
            }
        });



    }

    @Override
    public void onResume() {
        super.onResume();
        if (index == 0) {
            initTab0();
        } else if (index == 1) {
            initTab1();
        } else if (index == 2) {
            initTab2();
        } else if (index == 3) {
            initTab3();
        }
    }

    private void initTab0() {

        binding.ll0.setVisibility(View.VISIBLE);

        List<LocalDate> allJingStart = NoteUtils.getAllJingStart();
        if (allJingStart.size() < 2) {
            binding.chat0.setNoDataText("数据不足，请至少添加两个月经开始日的数据");
            return;
        }
        List<BarEntry> barEntries = new ArrayList<>();
        int maxEntries = Math.min(6, allJingStart.size() - 1); // 确保不超过可用数据量

        for (int i = 0; i < maxEntries; i++) {
            LocalDate currentDate = allJingStart.get(i);
            LocalDate nextDate = allJingStart.get(i + 1);
            long daysDifference = ChronoUnit.DAYS.between(currentDate, nextDate);
            barEntries.add(new BarEntry(i, Math.abs(daysDifference)));
        }

        BarDataSet barDataSet = new BarDataSet(barEntries, "");
        barDataSet.setColor(Color.parseColor("#FF557C"));
        barDataSet.setValueTextColor(Color.BLACK);
        barDataSet.setValueTextSize(12f);
        Legend legend = binding.chat0.getLegend();
        legend.setEnabled(false);
        BarData barData = new BarData(barDataSet);
        int screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        int dataCount = barEntries.size();
        float minBarWidth = 90f;
        float barWidth = (minBarWidth / screenWidth ) * dataCount;
        barData.setBarWidth(barWidth);

        binding.chat0.setTouchEnabled(false);
        binding.chat0.setData(barData);
        XAxis xAxis = binding.chat0.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if (index >= 0 && index < allJingStart.size()) {
                    return allJingStart.get(index).format(MM_DD_FORMATTER);
                }
                return "";
            }
        });
        xAxis.setDrawGridLines(false); // 不绘制X轴网格线

        YAxis leftYAxis = binding.chat0.getAxisLeft();
        YAxis rightYAxis = binding.chat0.getAxisRight();
        leftYAxis.setGridColor(Color.parseColor("#cccccc"));
        rightYAxis.setGridColor(Color.parseColor("#cccccc"));

        binding.chat0.getAxisRight().setEnabled(false);
        binding.chat0.getDescription().setEnabled(false);
        binding.chat0.setScaleEnabled(false);
    }

    private void initTab1() {
        binding.ll1.setVisibility(View.VISIBLE);
        List<LocalDate> allJingStart = NoteUtils.getAllJingStart();
        List<LocalDate> allJingEnd = NoteUtils.getAllJingEnd();

//        if (allJingStart.size() < 2 || allJingEnd.size() < 2) {
//            binding.chat1.setNoDataText("数据不足，请至少添加两个月经开始和结束的数据");
//            return;
//        }
        List<BarEntry> barEntries = new ArrayList<>();
        for (int i = 0; i < allJingStart.size(); i++) {
            LocalDate start = allJingStart.get(i);
            //找出距离月经开始日 10天内最大的日期，既为月经结束日，如果没有则按照固定的长度预测
            LocalDate end = allJingEnd.stream()
                    .filter(date ->start.isBefore(date) && start.plusDays(10).isAfter(date))
                    .max(LocalDate::compareTo).orElse(null);

            //没有明确记录结束日期的不计入
            if (end != null) {
                if (barEntries.size() <= 6) {
                    long daysDifference = ChronoUnit.DAYS.between(start, end);
                    barEntries.add(new BarEntry(i, Math.abs(daysDifference)));
                } else {
                    break;
                }
            }
        }

        BarDataSet barDataSet = new BarDataSet(barEntries, "");
        barDataSet.setColor(Color.parseColor("#FF557C"));
        barDataSet.setValueTextColor(Color.BLACK);
        barDataSet.setValueTextSize(12f);
        Legend legend = binding.chat1.getLegend();
        legend.setEnabled(false);
        BarData barData = new BarData(barDataSet);
        int screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        int dataCount = barEntries.size();
        float minBarWidth = 90f;
        float barWidth = (minBarWidth / screenWidth ) * dataCount;
        barData.setBarWidth(barWidth);
        binding.chat1.setTouchEnabled(false);
        binding.chat1.setData(barData);
        XAxis xAxis = binding.chat1.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if (index >= 0 && index < allJingStart.size()) {
                    return allJingStart.get(index).format(MM_DD_FORMATTER);
                }
                return "";
            }
        });
        xAxis.setDrawGridLines(false); // 不绘制X轴网格线
        YAxis leftYAxis = binding.chat0.getAxisLeft();
        YAxis rightYAxis = binding.chat0.getAxisRight();
        leftYAxis.setGridColor(Color.parseColor("#cccccc"));
        rightYAxis.setGridColor(Color.parseColor("#cccccc"));
        binding.chat1.getAxisRight().setEnabled(false);
        binding.chat1.getDescription().setEnabled(false);
        binding.chat1.setScaleEnabled(false);
    }

    private void initTab2() {
        binding.ll2.setVisibility(View.VISIBLE);
        List<Entry> entries = new ArrayList<>();
        List<NoteUtils.DayNote> allNotes12 = SexStatisticsUtils.getAllNotes12();
        List<NoteUtils.DayNote> filteredNotes = allNotes12.stream()
                .filter(dayNote -> dayNote.weight != null)  // 过滤掉temperature为null的对象
                .filter(dayNote -> !dayNote.weight.trim().isEmpty())  // 可选：过滤掉空字符串或纯空格的情况
                .collect(Collectors.toList());

        int maxEntries = Math.min(6, filteredNotes.size()); // 确保不超过可用数据量
        List<LocalDate> titles = new ArrayList<>();

        for (int i = 0; i < maxEntries; i++) {
            NoteUtils.DayNote dayNote = filteredNotes.get(i);
            if (!TextUtils.isEmpty(dayNote.weight)) {
                entries.add(new BarEntry(i, Float.parseFloat(dayNote.weight)));
                titles.add(LocalDate.parse(dayNote.date));
            }
        }

        LineDataSet dataSet = new LineDataSet(entries, "示例数据");
        dataSet.setColor(Color.parseColor("#A6E24A"));  // 线的颜色
        dataSet.setValueTextColor(getResources().getColor(R.color.black));  // 值的颜色
        dataSet.setCircleColor(Color.parseColor("#A6E24A"));
        dataSet.setDrawCircleHole(false);
        dataSet.setValueTextSize(12f);
        Legend legend = binding.chat2.getLegend();
        legend.setEnabled(false);
        LineData lineData = new LineData(dataSet);
        binding.chat2.setData(lineData);
        XAxis xAxis = binding.chat2.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if (index >= 0 && index < titles.size()) {
                    return titles.get(index).format(MM_DD_FORMATTER);
                }
                return "";
            }
        });
        xAxis.setDrawGridLines(false); // 不绘制X轴网格线
        YAxis leftYAxis = binding.chat2.getAxisLeft();
        YAxis rightYAxis = binding.chat2.getAxisRight();
        leftYAxis.setGridColor(Color.parseColor("#cccccc"));
        rightYAxis.setGridColor(Color.parseColor("#cccccc"));

        binding.chat2.getAxisRight().setEnabled(false);
        binding.chat2.getDescription().setEnabled(false);
        binding.chat2.setScaleEnabled(false);
        binding.chat2.setTouchEnabled(false);
    }

    private void initTab3() {
        binding.ll3.setVisibility(View.VISIBLE);
        List<Entry> entries = new ArrayList<>();
        List<NoteUtils.DayNote> allNotes12 = SexStatisticsUtils.getAllNotes12();
        List<NoteUtils.DayNote> filteredNotes = allNotes12.stream()
                .filter(dayNote -> dayNote.temperature != null)  // 过滤掉temperature为null的对象
                .filter(dayNote -> !dayNote.temperature.trim().isEmpty())  // 可选：过滤掉空字符串或纯空格的情况
                .collect(Collectors.toList());

        int maxEntries = Math.min(6, filteredNotes.size()); // 确保不超过可用数据量
        List<LocalDate> titles = new ArrayList<>();

        for (int i = 0; i < maxEntries; i++) {
            NoteUtils.DayNote dayNote = filteredNotes.get(i);
            if (!TextUtils.isEmpty(dayNote.temperature)) {
                entries.add(new BarEntry(i, Float.parseFloat(dayNote.temperature)));
                titles.add(LocalDate.parse(dayNote.date));
            }
        }

        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(Color.parseColor("#A6E24A"));  // 线的颜色
        dataSet.setValueTextColor(getResources().getColor(R.color.black));  // 值的颜色
        dataSet.setCircleColor(Color.parseColor("#A6E24A"));
        dataSet.setDrawCircleHole(false);
        dataSet.setValueTextSize(12f);
        LineData lineData = new LineData(dataSet);
        binding.chat3.setData(lineData);
        Legend legend = binding.chat3.getLegend();
        legend.setEnabled(false);
        XAxis xAxis = binding.chat3.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if (index >= 0 && index < titles.size()) {
                    return titles.get(index).format(MM_DD_FORMATTER);
                }
                return "";
            }
        });
        xAxis.setDrawGridLines(false); // 不绘制X轴网格线
        YAxis leftYAxis = binding.chat3.getAxisLeft();
        YAxis rightYAxis = binding.chat3.getAxisRight();
        leftYAxis.setGridColor(Color.parseColor("#cccccc"));
        rightYAxis.setGridColor(Color.parseColor("#cccccc"));

        binding.chat3.getAxisRight().setEnabled(false);
        binding.chat3.getDescription().setEnabled(false);
        binding.chat3.setScaleEnabled(false);
        binding.chat3.setTouchEnabled(false);
    }

}
